<template>
  <a-modal
    v-model:open="modalVisible"
    title="导出到知识图谱"
    width="600px"
    @ok="handleExport"
    @cancel="handleCancel"
    :confirm-loading="exporting"
  >
    <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <a-form-item label="导出范围">
        <a-radio-group v-model:value="exportType">
          <a-radio value="all">导出全部对象</a-radio>
          <a-radio value="selected">导出选中对象</a-radio>
        </a-radio-group>
      </a-form-item>

      <a-form-item v-if="exportType === 'selected'" label="选择对象">
        <a-select
          v-model:value="selectedObjectIds"
          mode="multiple"
          placeholder="请选择要导出的对象"
          style="width: 100%"
          show-search
          :filter-option="filterOption"
          :max-tag-count="3"
        >
          <a-select-option v-for="obj in allObjects" :key="obj.id" :value="obj.id">
            {{ obj.name }} ({{ obj.code }})
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="包含关系">
        <a-switch v-model:checked="includeRelationships" />
        <span style="margin-left: 8px; color: #666">
          是否同时导出对象之间的关系
        </span>
      </a-form-item>

      <a-form-item label="清除已有数据">
        <a-switch v-model:checked="clearExisting" />
        <span style="margin-left: 8px; color: #ff4d4f">
          警告: 将删除知识图谱中已存在的态势对象数据
        </span>
      </a-form-item>

      <a-alert
        message="导出说明"
        type="info"
        show-icon
        style="margin-top: 16px"
      >
        <template #description>
          <ul style="margin: 0; padding-left: 20px">
            <li>导出操作会将态势对象数据同步到 Neo4j 知识图谱</li>
            <li>每个对象将作为一个节点存储在图谱中</li>
            <li>如果包含关系，对象间的关系将作为边存储</li>
            <li>导出过程可能需要一些时间，请耐心等待</li>
          </ul>
        </template>
      </a-alert>

      <div v-if="exportResult" style="margin-top: 16px">
        <a-alert
          :message="exportResult.success ? '导出成功' : '导出失败'"
          :type="exportResult.success ? 'success' : 'error'"
          show-icon
        >
          <template #description>
            <div v-if="exportResult.success">
              <p>成功导出 {{ exportResult.objects_exported }} 个对象</p>
              <p v-if="includeRelationships">成功导出 {{ exportResult.relationships_exported }} 个关系</p>
            </div>
            <div v-else>
              <p>{{ exportResult.message }}</p>
              <ul v-if="exportResult.errors && exportResult.errors.length > 0" style="margin: 8px 0 0 20px">
                <li v-for="(error, index) in exportResult.errors.slice(0, 5)" :key="index">
                  {{ error }}
                </li>
                <li v-if="exportResult.errors.length > 5">
                  ...还有 {{ exportResult.errors.length - 5 }} 个错误
                </li>
              </ul>
            </div>
          </template>
        </a-alert>
      </div>
    </a-form>
  </a-modal>
</template>

<script setup>
import { ref, reactive, watch, computed, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { exportToKnowledgeGraph, getSituationObjects } from '@/apis'

const props = defineProps({
  open: Boolean
})

const emit = defineEmits(['update:open', 'success'])

const visible = ref(false)

// 计算属性处理 v-model:open
const modalVisible = computed({
  get: () => props.open,
  set: (val) => emit('update:open', val)
})
const exporting = ref(false)
const exportResult = ref(null)

const exportType = ref('all')
const selectedObjectIds = ref([])
const includeRelationships = ref(true)
const clearExisting = ref(false)

const allObjects = ref([])

watch(() => props.open, (val) => {
  visible.value = val
  if (val) {
    resetForm()
    loadAllObjects()
  }
})

watch(visible, (val) => {
  emit('update:open', val)
})

// 注意：不在 onMounted 中预加载数据，只在弹窗打开时加载
// 这样可以避免重复请求，并确保数据是最新的

// 加载所有对象
async function loadAllObjects() {
  try {
    console.log('[知识图谱导出] 开始加载态势对象列表...')

    // 由于后端限制 page_size 最大为 100，需要分页加载所有数据
    let allItems = []
    let page = 1
    const pageSize = 100
    let hasMore = true

    while (hasMore) {
      const response = await getSituationObjects({ page, page_size: pageSize })
      allItems = allItems.concat(response.items || [])

      // 检查是否还有更多数据
      if (response.items.length < pageSize || allItems.length >= response.total) {
        hasMore = false
      } else {
        page++
      }
    }

    allObjects.value = allItems
    console.log('[知识图谱导出] 加载成功，对象总数:', allItems.length)
  } catch (error) {
    console.error('[知识图谱导出] 加载对象列表失败:', error)

    let errorMsg = '未知错误'
    if (error instanceof Error) {
      errorMsg = error.message
    } else if (typeof error === 'string') {
      errorMsg = error
    } else if (error && error.toString) {
      errorMsg = error.toString()
    }

    message.error('加载对象列表失败: ' + errorMsg)
  }
}

// 重置表单
function resetForm() {
  exportType.value = 'all'
  selectedObjectIds.value = []
  includeRelationships.value = true
  clearExisting.value = false
  exportResult.value = null
}

// 执行导出
async function handleExport() {
  if (exportType.value === 'selected' && selectedObjectIds.value.length === 0) {
    message.error('请至少选择一个对象')
    return
  }

  if (clearExisting.value) {
    // 二次确认
    const confirmed = await new Promise(resolve => {
      Modal.confirm({
        title: '确认清除已有数据?',
        content: '这将删除知识图谱中所有已存在的态势对象数据，该操作不可恢复!',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk: () => resolve(true),
        onCancel: () => resolve(false)
      })
    })

    if (!confirmed) {
      return
    }
  }

  exporting.value = true
  exportResult.value = null

  try {
    const requestData = {
      object_ids: exportType.value === 'selected' ? selectedObjectIds.value : null,
      include_relationships: includeRelationships.value,
      clear_existing: clearExisting.value
    }

    const response = await exportToKnowledgeGraph(requestData)
    exportResult.value = response

    if (response.success) {
      message.success('导出成功!')
      emit('success')

      // 2秒后自动关闭弹窗
      setTimeout(() => {
        visible.value = false
      }, 2000)
    } else {
      message.error('导出失败: ' + response.message)
    }
  } catch (error) {
    message.error('导出失败: ' + error.message)
    exportResult.value = {
      success: false,
      message: error.message,
      objects_exported: 0,
      relationships_exported: 0,
      errors: [error.message]
    }
  } finally {
    exporting.value = false
  }
}

// 搜索过滤
function filterOption(input, option) {
  return option.children[0].toLowerCase().indexOf(input.toLowerCase()) >= 0
}

// 关闭弹窗
function handleCancel() {
  visible.value = false
}
</script>

<style scoped>
:deep(.ant-alert-with-description .ant-alert-description) {
  font-size: 13px;
}
</style>
